package org.windblog.core.servlet.post;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.windblog.core.CategoryService;
import org.windblog.core.PostService;
import org.windblog.core.entity.*;

import com.google.appengine.api.datastore.KeyFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class SetPostServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Post post = null;
		String edit = request.getParameter("edit");
		if (edit != null) {
			post = PostService.getPost(edit);
		} else {
			post = new Post();
			post.setDate(new Date());
			PostService.setPost(post);
		}
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		String excerpt = request.getParameter("excerpt");
		String commentStatus = null;
		if (request.getParameterValues("allowComments") == null
				|| request.getParameterValues("allowComments").length == 0) {
			commentStatus = "NO_COMMENTS";
		} else {
			commentStatus = "ALLOW_COMMENTS";
		}
		String[] categoriesParam = request.getParameterValues("categories");
		List<Category> categories = new LinkedList<Category>();
		if (categoriesParam != null) {
			for (String catName : categoriesParam) {
				categories.add(CategoryService.getCategory(catName));
			}
		}

		post.setTitle(title);
		post.setContent(content);
		post.setExcerpt(excerpt);
		post.setCommentStatus(commentStatus);

		List<Category> postCategories = post.getCategories();
		List<Category> allCategories = CategoryService.getCategories();
		for (Category cat : allCategories) {
			if (categories.contains(cat) && !postCategories.contains(cat)) {
				CategoryService.addPostToCategory(cat, post);
			} else if (!categories.contains(cat)
					&& postCategories.contains(cat)) {
				CategoryService.deletePostFromCategory(cat, post);
			}
		}

		PostService.savePost(post);
		String postkey = KeyFactory.keyToString(post.getKey());

		response.sendRedirect("/admin/post.jsp?action=edit&post=" + postkey
				+ "&message=1");
	}
}
